<template>
  <el-dialog :title="title" :visible.sync="visible" class="dialog-sm" append-to-body @close="visible = false">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" v-loading="loading">
      <el-form-item label="字典名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入字典名称" maxlength="64"/>
      </el-form-item>
      <el-form-item label="字典类型" prop="type">
        <el-input v-model="form.type" placeholder="请输入字典类型" maxlength="64"/>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" maxlength="250"/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleSubmit" :loading="submitting" :disabled="loading">确 定</el-button>
      <el-button @click="visible = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addTypeApi, infoTypeApi, editTypeApi } from '@/api/system/dict/type'

export default {
  name: 'DictForm',
  props: {
    value: Boolean,
    row: Object,
    moduleName: String
  },
  data() {
    return {
      title: '',
      loading: false,
      submitting: false,
      form: {
        name: undefined,
        type: undefined,
        status: '1',
        remark: undefined
      },
      rules: {
        name: [{ required: true, message: '字典名称不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '字典类型不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    visible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      this.loading = true
      this.form.id = this.row?.id || undefined
      if (this.form.id) {
        this.title = '修改' + this.moduleName
        await this.getRowData()
      } else {
        this.title = '添加' + this.moduleName
      }
      this.loading = false
    },
    async getRowData() {
      try {
        const { info } = await infoTypeApi(this.form.id)
        this.form = this.dataToForm(this.form, info)
      } catch (error) {
        this.visible = false
      }
    },
    handleSubmit() {
      this.$refs.formRef.validate(async valid => {
        if (!valid || this.submitting) return
        this.submitting = true
        try {
          await this.$modal.confirm('确定提交表单数据？')
          if (this.form.id) {
            await editTypeApi(this.form)
          } else {
            await addTypeApi(this.form)
          }
          this.$emit('submit')
          this.$modal.msgSuccess('操作成功')
          this.visible = false
        } catch (e) {
          this.submitting = false
        }
      })
    }
  }
}
</script>
